#ifndef _MY_SERVO_H_
#define _MY_SERVO_H_

#define SERVO_DURATION_MIN      500
#define SERVO_DURATION_NEUTRAL  1500
#define SERVO_DURATION_MAX      2500

class MyServo {
public:
    MyServo () {
    }

    void attach (int pin) {
        this->pin = pin;
        pinMode (pin, OUTPUT);
    }
    
    void write (int angle) {
        double a = angle;
        if (a < 0) a = 0;
        if (a > 180) a = 180;
        
        Serial.print ("angle = ");
        Serial.println (angle);
  
        int pulsewidth = 500 + 100 * a / 9;         //将角度转化为500-2480的脉宽值  
        if (pulsewidth < SERVO_DURATION_MIN) {
            pulsewidth = SERVO_DURATION_MIN;
        }
        if (pulsewidth > SERVO_DURATION_MAX) {
            pulsewidth = SERVO_DURATION_MAX;
        }

        Serial.print ("pluse width = ");
        Serial.println (pulsewidth);
  
        //发送50个脉冲  
        for(int i=0;i<75;i++){  
            digitalWrite(pin, HIGH);                //将舵机接口电平至高  
            delayMicroseconds(pulsewidth);          //延时脉宽值的微秒数  
            digitalWrite(pin, LOW);                 //将舵机接口电平至低  
            delayMicroseconds(20000 - pulsewidth);  
        }  
        delay(100);  
    }

private:
    int pin;
};
#endif
